package com.quzi.kettle.push;

import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;

import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.quzi.kettle.bean.ChannelObject;


public class PushCallback implements MqttCallback {

    private ContextWrapper context;
    public static final String IMAction = "IM-kettle";

    public PushCallback(ContextWrapper context) {

        this.context = context;
    }

    @Override
    public void connectionLost(Throwable cause) {
        //We should reconnect here
    	Intent intent = new Intent();
    	Log.d("mmmqtt","connection lost");
		intent.setAction(IMAction);
		ChannelObject obj = new ChannelObject();
		obj.setDataType(ChannelObject.LOST_CONNECT);
		intent.putExtra("data", obj);
		context.sendBroadcast(intent);
    }

    @Override
    public void messageArrived(MqttTopic topic, MqttMessage message) throws Exception {
    	Log.d("mmmqtt","messageArrived");
    	Intent intent = new Intent();
		Bundle bundle = new Bundle();
		ChannelObject obj = new ChannelObject();
		intent.setAction(IMAction);
		obj.setData(message.getPayload());
		obj.setDataType(topic.getName().contains("receive") ? ChannelObject.RECEIVE:ChannelObject.SEND);
		bundle.putSerializable("data", obj);
		intent.putExtras(bundle);
		context.sendBroadcast(intent);
    }

    @Override
    public void deliveryComplete(MqttDeliveryToken token) {
        //We do not need this because we do not publish
    }
}
